<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">
<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://chenjiabing666.github.io/"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>


  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-flash.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="code-ltfpVmGDr3" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Mybatis," />





  <link rel="alternate" href="/atom.xml" title="不才陈某技术博客" type="application/atom+xml" />






<meta name="description" content="前言
上一篇文章介绍了Mybatis基础的CRUD操作、常用的标签、属性等内容，如果对部分不熟悉的朋友可以看Mybatis入门之基本操作。
本篇文章继续讲解Mybatis的结果映射的内容，想要在企业开发中灵活的使用Mybatis，这部分的内容是必须要精通的。

什么是结果映射？
简单的来说就是一条SQL查询语句返回的字段如何与Java实体类中的属性相对应。
如下一条SQL语句，查询患者的用户id，">
<meta property="og:type" content="article">
<meta property="og:title" content="Mybatis入门之结果映射">
<meta property="og:url" content="https://chenjiabing666.github.io/2020/04/20/Mybatis入门之结果映射/index.html">
<meta property="og:site_name" content="不才陈某技术博客">
<meta property="og:description" content="前言
上一篇文章介绍了Mybatis基础的CRUD操作、常用的标签、属性等内容，如果对部分不熟悉的朋友可以看Mybatis入门之基本操作。
本篇文章继续讲解Mybatis的结果映射的内容，想要在企业开发中灵活的使用Mybatis，这部分的内容是必须要精通的。

什么是结果映射？
简单的来说就是一条SQL查询语句返回的字段如何与Java实体类中的属性相对应。
如下一条SQL语句，查询患者的用户id，">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/Mybatis-%E7%BB%93%E6%9E%9C%E6%98%A0%E5%B0%84/1.png">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/Mybatis-%E7%BB%93%E6%9E%9C%E6%98%A0%E5%B0%84/2.jpg">
<meta property="og:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/%E4%B8%83%E7%A7%92%E7%BC%96%E7%A8%8B.jpg">
<meta property="og:updated_time" content="2020-10-23T11:01:48.947Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Mybatis入门之结果映射">
<meta name="twitter:description" content="前言
上一篇文章介绍了Mybatis基础的CRUD操作、常用的标签、属性等内容，如果对部分不熟悉的朋友可以看Mybatis入门之基本操作。
本篇文章继续讲解Mybatis的结果映射的内容，想要在企业开发中灵活的使用Mybatis，这部分的内容是必须要精通的。

什么是结果映射？
简单的来说就是一条SQL查询语句返回的字段如何与Java实体类中的属性相对应。
如下一条SQL语句，查询患者的用户id，">
<meta name="twitter:image" content="https://gitee.com/chenjiabing666/Blog-file/raw/master/Mybatis-%E7%BB%93%E6%9E%9C%E6%98%A0%E5%B0%84/1.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"always","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://chenjiabing666.github.io/2020/04/20/Mybatis入门之结果映射/"/>





  <title>Mybatis入门之结果映射 | 不才陈某技术博客</title>
  








</head>



<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">不才陈某技术博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信公众号：码猿技术专栏</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://chenjiabing666.github.io/2020/04/20/Mybatis入门之结果映射/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="不才陈某">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="不才陈某技术博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Mybatis入门之结果映射</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-04-20T17:00:43+08:00">
                2020-04-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Mybatis进阶/" itemprop="url" rel="index">
                    <span itemprop="name">Mybatis进阶</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/04/20/Mybatis入门之结果映射/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2020/04/20/Mybatis入门之结果映射/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
		  
		  
			  <span class="post-meta-divider">|</span>
			  <span id="busuanzi_value_page_pv"></span>次阅读
			

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.8k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  15
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><ul>
<li>上一篇文章介绍了Mybatis基础的CRUD操作、常用的标签、属性等内容，如果对部分不熟悉的朋友可以看<a href="https://mp.weixin.qq.com/s/KdrEvlShnVoYA8nr0qLSNw" target="_blank" rel="external">Mybatis入门之基本操作</a>。</li>
<li>本篇文章继续讲解Mybatis的结果映射的内容，想要在企业开发中灵活的使用Mybatis，这部分的内容是必须要精通的。</li>
</ul>
<h2 id="什么是结果映射？"><a href="#什么是结果映射？" class="headerlink" title="什么是结果映射？"></a>什么是结果映射？</h2><ul>
<li>简单的来说就是一条<code>SQL查询语句</code>返回的字段如何与<code>Java实体类</code>中的属性相对应。</li>
<li><p>如下一条SQL语句，查询患者的用户id，科室id，主治医生id：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">'selectPatientInfos'</span> <span class="attr">resultType</span>=<span class="string">'com.xxx.domain.PatientInfo'</span>&gt;</span></div><div class="line">  select user_id,dept_id,doc_id from patient_info;</div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>Java实体类<code>PatientInfo</code>如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Data</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PatientInfo</span></span>&#123;</div><div class="line">  <span class="keyword">private</span> String userId;</div><div class="line">  <span class="keyword">private</span> String deptId;</div><div class="line">  <span class="keyword">private</span> String docId;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>程序员写这条SQL的目的就是想查询出来的<code>user_id</code>,<code>dept_id</code>,<code>doc_id</code>分别赋值给实体类中的<code>userId</code>,<code>deptId</code>,<code>docId</code>。这就是简单的结果映射。</p>
</li>
</ul>
<h2 id="如何映射？"><a href="#如何映射？" class="headerlink" title="如何映射？"></a>如何映射？</h2><ul>
<li>Myabtis中的结果映射有很多种方式，下面会逐一介绍。</li>
</ul>
<h3 id="别名映射"><a href="#别名映射" class="headerlink" title="别名映射"></a>别名映射</h3><ul>
<li><p>这个简单，保持查询的SQL返回的字段和Java实体类一样即可，比如上面例子的SQL可以写成：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">'selectPatientInfos'</span> <span class="attr">resultType</span>=<span class="string">'com.xxx.domain.PatientInfo'</span>&gt;</span></div><div class="line">   select user_id as userId,</div><div class="line">   dept_id as deptId,</div><div class="line">   doc_id as docId</div><div class="line">   from patient_info; </div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>这样就能和实体类中的属性映射成功了。</p>
</li>
</ul>
<h3 id="驼峰映射"><a href="#驼峰映射" class="headerlink" title="驼峰映射"></a>驼峰映射</h3><ul>
<li><p>Mybatis提供了驼峰命名映射的方式，比如数据库中的<code>user_id</code>这个字段，能够自动映射到<code>userId</code>属性。那么此时的查询的SQL变成如下即可：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">'selectPatientInfos'</span> <span class="attr">resultType</span>=<span class="string">'com.xxx.domain.PatientInfo'</span>&gt;</span></div><div class="line">    select user_id,dept_id,doc_id from patient_info;</div><div class="line">  <span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>如何开启呢？与SpringBoot整合后开启其实很简单，有两种方式，一个是配置文件中开启，一个是配置类开启。</p>
</li>
</ul>
<h4 id="配置文件开启驼峰映射"><a href="#配置文件开启驼峰映射" class="headerlink" title="配置文件开启驼峰映射"></a>配置文件开启驼峰映射</h4><ul>
<li>只需要在<code>application.properties</code>文件中添加如下一行代码即可：<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">mybatis.configuration.map-underscore-to-camel-case=true</div></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="配置类中开启驼峰映射【简单了解，后续源码章节着重介绍】"><a href="#配置类中开启驼峰映射【简单了解，后续源码章节着重介绍】" class="headerlink" title="配置类中开启驼峰映射【简单了解，后续源码章节着重介绍】"></a>配置类中开启驼峰映射【简单了解，后续源码章节着重介绍】</h4><ul>
<li>这种方式需要你对源码有一定的了解，上一篇入门教程中有提到，Mybatis与Springboot整合后适配了一个starter，那么肯定会有自动配置类，Mybatis的自动配置类是<code>MybatisAutoConfiguration</code>，其中有这么一段代码，如下：<br><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/Mybatis-%E7%BB%93%E6%9E%9C%E6%98%A0%E5%B0%84/1.png" alt=""></li>
<li><p><code>@ConditionalOnMissingBean</code>这个注解的意思就是当IOC容器中没有<code>SqlSessionFactory</code>这个Bean对象这个配置才会生效;<code>applyConfiguration(factory)</code>这行代码就是创建一个<code>org.apache.ibatis.session.Configuration</code>赋值给<code>SqlSessionFactoryBean</code>。源码分析到这，应该很清楚了，无非就是自己在容器中创建一个<code>SqlSessionFactory</code>，然后设置属性即可，如下代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Bean</span>(<span class="string">"sqlSessionFactory"</span>)</div><div class="line"><span class="function"><span class="keyword">public</span> SqlSessionFactory <span class="title">sqlSessionFactory</span><span class="params">(DataSource dataSource)</span> <span class="keyword">throws</span> Exception </span>&#123;</div><div class="line">    SqlSessionFactoryBean sqlSessionFactoryBean = <span class="keyword">new</span> SqlSessionFactoryBean();</div><div class="line">    <span class="comment">//设置数据源</span></div><div class="line">    sqlSessionFactoryBean.setDataSource(dataSource);</div><div class="line">    <span class="comment">//设置xml文件的位置</span></div><div class="line">    sqlSessionFactoryBean.setMapperLocations(<span class="keyword">new</span> PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATOIN));</div><div class="line">    <span class="comment">//创建Configuration</span></div><div class="line">    org.apache.ibatis.session.Configuration configuration = <span class="keyword">new</span> org.apache.ibatis.session.Configuration();</div><div class="line">    <span class="comment">// 开启驼峰命名映射</span></div><div class="line">    configuration.setMapUnderscoreToCamelCase(<span class="keyword">true</span>);</div><div class="line">    configuration.setDefaultFetchSize(<span class="number">100</span>);</div><div class="line">    configuration.setDefaultStatementTimeout(<span class="number">30</span>);</div><div class="line">    sqlSessionFactoryBean.setConfiguration(configuration);</div><div class="line">    <span class="comment">//将typehandler注册到mybatis</span></div><div class="line">    sqlSessionFactoryBean.setTypeHandlers(typeHandlers());</div><div class="line">    <span class="keyword">return</span> sqlSessionFactoryBean.getObject();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p><strong>注意</strong>：如果对<code>SqlSessionFactory</code>没有特殊定制，不介意重写，因为这会自动覆盖自动配置类中的配置。</p>
</li>
</ul>
<h3 id="resultMap映射"><a href="#resultMap映射" class="headerlink" title="resultMap映射"></a>resultMap映射</h3><ul>
<li>什么是<code>resultMap</code>？简单的说就是一个类似Map的结构，将数据库中的字段和JavaBean中的属性字段对应起来，这样就能做到一一映射了。</li>
<li><p>上述的例子使用resultMap又会怎么写呢？如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="comment">&lt;!--创建一个resultMap映射--&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">"patResultMap"</span> <span class="attr">type</span>=<span class="string">"com.xxx.domain.PatientInfo"</span>&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">id</span> <span class="attr">property</span>=<span class="string">"userId"</span> <span class="attr">column</span>=<span class="string">"user_id"</span> /&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">"docId"</span> <span class="attr">column</span>=<span class="string">"doc_id"</span>/&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">result</span> <span class="attr">property</span>=<span class="string">"deptId"</span> <span class="attr">column</span>=<span class="string">"dept_id"</span>/&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></div><div class="line"></div><div class="line"><span class="comment">&lt;!--使用resultMap映射结果到com.xxx.domain.PatientInfo这个Bean中--&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">'selectPatientInfos'</span> <span class="attr">resultMap</span>=<span class="string">'patResultMap'</span>&gt;</span></div><div class="line">    select user_id,dept_id,doc_id from patient_info;</div><div class="line">  <span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>其实很简单，就是创建一个<code>&lt;resultMap&gt;</code>，然后<code>&lt;select&gt;</code>标签指定这个resultMap即可。</p>
</li>
<li><p><code>&lt;resultMap&gt;</code>的属性如下：</p>
<ul>
<li><code>id</code>：唯一标识这个resultMap，同一个Mapper.xml中不能重复</li>
<li><code>type</code>：指定JavaBean的类型，可以是全类名，也可以是别名</li>
</ul>
</li>
<li>子标签<code>&lt;result&gt;</code>的属性如下：<ul>
<li><code>column</code>：SQL返回的字段名称</li>
<li><code>property</code>：JavaBean中属性的名称</li>
<li><code>javaType</code>：一个 Java 类的全限定名，或一个类型别名（关于内置的类型别名，可以参考上面的表格）。 如果你映射到一个 JavaBean，MyBatis 通常可以推断类型。然而，如果你映射到的是 HashMap，那么你应该明确地指定 javaType 来保证行为与期望的相一致。</li>
<li><code>jdbcType</code>：JDBC 类型，所支持的 JDBC 类型参见这个表格之后的“支持的 JDBC 类型”。 只需要在可能执行插入、更新和删除的且允许空值的列上指定 JDBC 类型。这是 JDBC 的要求而非 MyBatis 的要求。如果你直接面向 JDBC 编程，你需要对可以为空值的列指定这个类型。</li>
<li><code>typeHandler</code>： 这个属性值是一个类型处理器实现类的全限定名，或者是类型别名。</li>
<li><code>resultMap</code>：结果映射的 ID，可以将此关联的嵌套结果集映射到一个合适的对象树中。 它可以作为使用额外 select 语句的替代方案。</li>
</ul>
</li>
</ul>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><ul>
<li>以上列举了三种映射的方式，分别是<strong>别名映射</strong>，<strong>驼峰映射</strong>、<strong><code>resultMap</code>映射</strong>。</li>
<li>你以为这就结束了？要是世界这么简单多好，做梦吧，哈哈！！！<br><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/Mybatis-%E7%BB%93%E6%9E%9C%E6%98%A0%E5%B0%84/2.jpg" alt=""></li>
</ul>
<h2 id="高级结果映射"><a href="#高级结果映射" class="headerlink" title="高级结果映射"></a>高级结果映射</h2><ul>
<li>MyBatis 创建时的一个思想是：数据库不可能永远是你所想或所需的那个样子。 我们希望每个数据库都具备良好的第三范式或 BCNF 范式，可惜它们并不都是那样。 如果能有一种数据库映射模式，完美适配所有的应用程序，那就太好了，但可惜也没有。 而 ResultMap 就是 MyBatis 对这个问题的答案。</li>
<li>我们知道在数据库的关系中一对一，多对一，一对多，多对多的关系，那么这种关系如何在Mybatis中体现并映射成功呢？</li>
</ul>
<h3 id="关联-association"><a href="#关联-association" class="headerlink" title="关联(association)"></a>关联(association)</h3><ul>
<li>关联（association）元素处理<strong>有一个</strong>类型的关系。 比如，在我们的示例中，一个员工属于一个部门。关联结果映射和其它类型的映射工作方式差不多。 你需要指定目标属性名以及属性的<code>javaType</code>（很多时候 MyBatis 可以自己推断出来），在必要的情况下你还可以设置 <code>JDBC</code> 类型，如果你想覆盖获取结果值的过程，还可以设置类型处理器。</li>
<li>关联的不同之处是，你需要告诉 MyBatis 如何加载关联。MyBatis 有两种不同的方式加载关联：<ul>
<li><code>嵌套 Select 查询</code>：通过执行另外一个 SQL 映射语句来加载期望的复杂类型。</li>
<li><code>嵌套结果映射</code>：使用嵌套的结果映射来处理连接结果的重复子集。</li>
</ul>
</li>
<li>首先，先让我们来看看这个元素的属性。你将会发现，和普通的结果映射相比，它只在 <code>select</code> 和 <code>resultMap</code> 属性上有所不同。<ul>
<li><code>property</code>：    映射到列结果的字段或属性。如果用来匹配的 JavaBean 存在给定名字的属性，那么它将会被使用。</li>
<li><code>javaType</code>：一个 Java 类的完全限定名，或一个类型别名（关于内置的类型别名，可以参考上面的表格）<br> <code>jdbcType</code>：    JDBC 类型， 只需要在可能执行插入、更新和删除的且允许空值的列上指定 JDBC 类型</li>
<li><code>typeHandler</code>：使用这个属性，你可以覆盖默认的类型处理器。 这个属性值是一个类型处理器实现类的完全限定名，或者是类型别名。<br> <code>column</code>：    数据库中的列名，或者是列的别名。一般情况下，这和传递给 <code>resultSet.getString(columnName)</code> 方法的参数一样。 注意：在使用复合主键的时候，你可以使用 <code>column=&quot;{prop1=col1,prop2=col2}&quot;</code> 这样的语法来指定多个传递给嵌套 Select 查询语句的列名。这会使得<code>prop1</code>和 <code>prop2</code> 作为参数对象，被设置为对应嵌套 Select 语句的参数。</li>
<li><code>select</code>：用于加载复杂类型属性的映射语句的 ID，它会从 column 属性指定的列中检索数据，作为参数传递给目标 select 语句。 具体请参考下面的例子。注意：在使用复合主键的时候，你可以使用<code>column=&quot;{prop1=col1,prop2=col2}&quot;</code> 这样的语法来指定多个传递给嵌套 Select 查询语句的列名。这会使得 prop1 和 prop2 作为参数对象，被设置为对应嵌套 Select 语句的参数。</li>
<li><code>fetchType</code>：可选的。有效值为 <code>lazy</code> 和 <code>eager</code>。 指定属性后，将在映射中忽略全局配置参数 <code>lazyLoadingEnabled</code>，使用属性的值。</li>
</ul>
</li>
</ul>
<h4 id="例子"><a href="#例子" class="headerlink" title="例子"></a>例子</h4><ul>
<li>一对一的关系比如：一个员工属于一个部门，那么数据库表就会在员工表中加一个部门的id作为逻辑外键。</li>
<li><p>创建员工JavaBean</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Data</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</div><div class="line">	<span class="keyword">private</span> Integer id;</div><div class="line">	<span class="keyword">private</span> String username;</div><div class="line">	<span class="keyword">private</span> String password;</div><div class="line">	<span class="keyword">private</span> Integer age;</div><div class="line">  <span class="keyword">private</span> Integer deptId;</div><div class="line">  <span class="comment">//部门</span></div><div class="line">	<span class="keyword">private</span> Department department;   </div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>部门JavaBean</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Data</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Department</span> </span>&#123;</div><div class="line">	<span class="keyword">private</span> Integer id;</div><div class="line">	<span class="keyword">private</span> String name;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>那么我们想要查询所有的用户信息和其所在的部门信息，此时的sql语句为:<code>select * from user u left join department d on u.department_id=d.id</code>;。但是我们在mybaits中如果使用这条语句查询，那么返回的结果类型是什么呢？如果是User类型的，那么查询结果返回的还有<code>Department</code>类型的数据，那么肯定会对应不上的。此时<code>&lt;resultMap&gt;</code>来了，它来了!!!</p>
</li>
</ul>
<h4 id="关联的嵌套-Select-查询【可以忽略】"><a href="#关联的嵌套-Select-查询【可以忽略】" class="headerlink" title="关联的嵌套 Select 查询【可以忽略】"></a>关联的嵌套 Select 查询【可以忽略】</h4><ul>
<li><p>查询员工和所在的部门在Mybatis如何写呢？代码如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">"userResult"</span> <span class="attr">type</span>=<span class="string">"com.xxx.domain.User"</span>&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">"id"</span> <span class="attr">property</span>=<span class="string">"id"</span>/&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"password"</span> <span class="attr">property</span>=<span class="string">"password"</span>/&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"age"</span> <span class="attr">property</span>=<span class="string">"age"</span>/&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"username"</span> <span class="attr">property</span>=<span class="string">"username"</span>/&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"dept_id"</span> <span class="attr">property</span>=<span class="string">"deptId"</span>/&gt;</span></div><div class="line">  <span class="comment">&lt;!--关联查询，select嵌套查询--&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">association</span> <span class="attr">property</span>=<span class="string">"department"</span> <span class="attr">column</span>=<span class="string">"dept_id"</span> <span class="attr">javaType</span>=<span class="string">"com.xxx.domain.Department"</span> <span class="attr">select</span>=<span class="string">"selectDept"</span>/&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></div><div class="line"></div><div class="line"><span class="comment">&lt;!--查询员工--&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectUser"</span> <span class="attr">resultMap</span>=<span class="string">"userResult"</span>&gt;</span></div><div class="line">  SELECT * FROM user WHERE id = #&#123;id&#125;</div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div><div class="line"></div><div class="line"><span class="comment">&lt;!--查询部门--&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectDept"</span> <span class="attr">resultType</span>=<span class="string">"com.xxx.domain.Department "</span>&gt;</span></div><div class="line">  SELECT * FROM department WHERE ID = #&#123;id&#125;</div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p>就是这么简单，两个select语句，一个用来加载员工，一个用来加载部门。</p>
</li>
<li>这种方式虽然很简单，但在大型数据集或大型数据表上表现不佳。这个问题被称为<code>N+1</code> 查询问题。 概括地讲，N+1 查询问题是这样子的：<ul>
<li>你执行了一个单独的 SQL 语句来获取结果的一个列表（就是<code>+1</code>）。</li>
<li>对列表返回的每条记录，你执行一个 <code>select</code> 查询语句来为每条记录加载详细信息（就是<code>N</code>）。</li>
</ul>
</li>
<li>这个问题会导致成百上千的 SQL 语句被执行。有时候，我们不希望产生这样的后果。</li>
</ul>
<h4 id="关联的嵌套结果映射【重点】"><a href="#关联的嵌套结果映射【重点】" class="headerlink" title="关联的嵌套结果映射【重点】"></a>关联的嵌套结果映射【重点】</h4><ul>
<li><code>&lt;association &gt;</code>标签中还可以直接嵌套结果映射，此时的Mybatis的查询如下：<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 定义resultMap --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">"UserDepartment"</span> <span class="attr">type</span>=<span class="string">"com.xxx.domain.User"</span> &gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">"user_id"</span> <span class="attr">property</span>=<span class="string">"id"</span>/&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"password"</span> <span class="attr">property</span>=<span class="string">"password"</span>/&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"age"</span> <span class="attr">property</span>=<span class="string">"age"</span>/&gt;</span></div><div class="line">	<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"username"</span> <span class="attr">property</span>=<span class="string">"username"</span>/&gt;</span></div><div class="line">  <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"dept_id"</span> <span class="attr">property</span>=<span class="string">"deptId"</span>/&gt;</span></div><div class="line">	</div><div class="line">	<span class="comment">&lt;!--</span></div><div class="line">		property: 指定User中对应的部门属性名称</div><div class="line">		javaType: 指定类型，可以是全类名或者别名</div><div class="line">	 --&gt;</div><div class="line">	<span class="tag">&lt;<span class="name">association</span> <span class="attr">property</span>=<span class="string">"department"</span> <span class="attr">javaType</span>=<span class="string">"com.xx.domain.Department"</span>&gt;</span></div><div class="line">    <span class="comment">&lt;!--指定Department中的属性映射，这里也可以使用单独拎出来，然后使用association中的resultMap属性指定--&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">"id"</span> <span class="attr">property</span>=<span class="string">"id"</span>/&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"dept_name"</span> <span class="attr">property</span>=<span class="string">"name"</span>/&gt;</span></div><div class="line">	<span class="tag">&lt;/<span class="name">association</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></div><div class="line"></div><div class="line"><span class="comment">&lt;!-- </span></div><div class="line">	resultMap: 指定上面resultMap的id的值</div><div class="line"> --&gt;</div><div class="line"> <span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"findUserAndDepartment"</span> <span class="attr">resultMap</span>=<span class="string">"UserDepartment"</span>&gt;</span></div><div class="line"> 	select </div><div class="line">   u.id as user_id,</div><div class="line">   u.dept_id,</div><div class="line">   u.name,</div><div class="line">   u.password,</div><div class="line">   u.age,</div><div class="line">   d.id,</div><div class="line">   d.name as dept_name</div><div class="line">   from user u left join department d on u.department_id=d.id</div><div class="line"> <span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="总结-1"><a href="#总结-1" class="headerlink" title="总结"></a>总结</h4><ul>
<li>至此<code>有一个</code>类型的关联已经完成了，学会一个<code>&lt;association&gt;</code>使用即能完成。</li>
<li><strong>注意</strong>： 关联的嵌套 Select 查询不建议使用，<code>N+1</code>是个重大问题，虽说Mybatis提供了延迟加载的功能，但是仍然不建议使用，企业开发中也是不常用的。</li>
</ul>
<h3 id="集合collection"><a href="#集合collection" class="headerlink" title="集合collection"></a>集合collection</h3><ul>
<li>集合，顾名思义，就是处理<code>有很多个</code>类型的关联。</li>
<li>其中的属性和<code>association</code>中的属性类似，不再重复了。</li>
<li><p>比如这样一个例子：查询一个部门中的全部员工，查询SQL如何写呢？如下：</p>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">select</span> * <span class="keyword">from</span> department d <span class="keyword">left</span> <span class="keyword">join</span> <span class="keyword">user</span> u <span class="keyword">on</span> u.department_id=d.id;</div></pre></td></tr></table></figure>
</li>
<li><p>此时的<code>User</code>实体类如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Data</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</div><div class="line"> <span class="keyword">private</span> Integer id;</div><div class="line"> <span class="keyword">private</span> String username;</div><div class="line"> <span class="keyword">private</span> String password;</div><div class="line"> <span class="keyword">private</span> Integer age;</div><div class="line"> <span class="keyword">private</span> Integer deptId; </div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>此时的<code>Department</code>实体类如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Data</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Department</span> </span>&#123;</div><div class="line"> <span class="keyword">private</span> Integer id;</div><div class="line"> <span class="keyword">private</span> String name;</div><div class="line"> <span class="keyword">private</span> List&lt;User&gt; users;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>和<code>association</code>类似，同样有两种方式，我们可以使用嵌套 Select 查询，或基于连接的嵌套结果映射集合。</p>
</li>
</ul>
<h3 id="集合的嵌套-Select-查询【可以忽略】"><a href="#集合的嵌套-Select-查询【可以忽略】" class="headerlink" title="集合的嵌套 Select 查询【可以忽略】"></a>集合的嵌套 Select 查询【可以忽略】</h3><ul>
<li><p>不太重要，查询如下：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">"deptResult"</span> <span class="attr">type</span>=<span class="string">"com.xxx.domain.Department"</span>&gt;</span></div><div class="line">  <span class="comment">&lt;!--指定Department中的属性映射，这里也可以使用单独拎出来，然后使用association中的resultMap属性指定--&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">"id"</span> <span class="attr">property</span>=<span class="string">"id"</span>/&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"name"</span> <span class="attr">property</span>=<span class="string">"name"</span>/&gt;</span></div><div class="line">  <span class="comment">&lt;!--</span></div><div class="line">  ofType：指定实际的JavaBean的全类型或者别名</div><div class="line">  select：指定嵌套的select查询</div><div class="line">  javaType：集合的类型，可以不写，Mybatis可以推测出来</div><div class="line">--&gt;</div><div class="line">  <span class="tag">&lt;<span class="name">collection</span> <span class="attr">property</span>=<span class="string">"users"</span> <span class="attr">javaType</span>=<span class="string">"java.util.ArrayList"</span> <span class="attr">column</span>=<span class="string">"id"</span> <span class="attr">ofType</span>=<span class="string">"com.xxx.doamin.User"</span> <span class="attr">select</span>=<span class="string">"selectByDeptId"</span>/&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></div><div class="line"></div><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectDept"</span> <span class="attr">resultMap</span>=<span class="string">"deptResult"</span>&gt;</span></div><div class="line">  SELECT * FROM department  WHERE ID = #&#123;id&#125;</div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div><div class="line"></div><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectByDeptId"</span> <span class="attr">resultType</span>=<span class="string">"com.xxx.domain.User"</span>&gt;</span></div><div class="line">  SELECT * FROM user WHERE dept_id = #&#123;id&#125;</div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
<li><p><strong>注意</strong>：这里出现了一个不同于<code>association</code>的属性<code>ofType</code>，这个属性非常重要，它用来将 JavaBean（或字段）属性的类型和集合存储的类型区分开来。</p>
</li>
</ul>
<h3 id="集合的嵌套结果映射【重点】"><a href="#集合的嵌套结果映射【重点】" class="headerlink" title="集合的嵌套结果映射【重点】"></a>集合的嵌套结果映射【重点】</h3><ul>
<li>现在你可能已经猜到了集合的嵌套结果映射是怎样工作的——除了新增的 <code>ofType</code> 属性，它和关联的完全相同。</li>
<li>此时的Mybatis查询如下：<figure class="highlight xml"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="comment">&lt;!--部门的resultMap--&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">"deptResult"</span> <span class="attr">type</span>=<span class="string">"com.xxx.domain.Department"</span>&gt;</span></div><div class="line">  <span class="comment">&lt;!--指定Department中的属性映射，这里也可以使用单独拎出来，然后使用association中的resultMap属性指定--&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">"dept_id"</span> <span class="attr">property</span>=<span class="string">"id"</span>/&gt;</span></div><div class="line">		<span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"dept_name"</span> <span class="attr">property</span>=<span class="string">"name"</span>/&gt;</span></div><div class="line">  <span class="comment">&lt;!--</span></div><div class="line">  ofType：指定实际的JavaBean的全类型或者别名</div><div class="line">  resultMap：指定员工的resultMap</div><div class="line">--&gt;</div><div class="line">  <span class="tag">&lt;<span class="name">collection</span> <span class="attr">property</span>=<span class="string">"users"</span> <span class="attr">ofType</span>=<span class="string">"com.xxx.doamin.User"</span> <span class="attr">resultMap</span>=<span class="string">'userResult'</span>/&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></div><div class="line"></div><div class="line"><span class="comment">&lt;!--员工的resultMap--&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">resultMap</span> <span class="attr">id</span>=<span class="string">"userResult"</span> <span class="attr">type</span>=<span class="string">"com.xxx.domain.User"</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">id</span> <span class="attr">column</span>=<span class="string">"user_id"</span> <span class="attr">property</span>=<span class="string">"id"</span>/&gt;</span></div><div class="line">   <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"password"</span> <span class="attr">property</span>=<span class="string">"password"</span>/&gt;</span></div><div class="line">   <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"age"</span> <span class="attr">property</span>=<span class="string">"age"</span>/&gt;</span></div><div class="line">   <span class="tag">&lt;<span class="name">result</span> <span class="attr">column</span>=<span class="string">"username"</span> <span class="attr">property</span>=<span class="string">"username"</span>/&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">resultMap</span>&gt;</span></div><div class="line"></div><div class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">id</span>=<span class="string">"selectDeptById"</span> <span class="attr">resultType</span>=<span class="string">"com.xxx.domain.Department"</span>&gt;</span></div><div class="line">  select </div><div class="line">  d.id as dept_id,</div><div class="line">  d.name as dept_name,</div><div class="line">  u.id as user_id,</div><div class="line">  u.password,</div><div class="line">  u.name</div><div class="line">  from department d left join user u on u.department_id=d.id</div><div class="line">  where d.id=#&#123;id&#125;</div><div class="line"><span class="tag">&lt;/<span class="name">select</span>&gt;</span></div></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="总结-2"><a href="#总结-2" class="headerlink" title="总结"></a>总结</h2><ul>
<li>至此Mybatis第二弹之结果映射已经写完了，如果觉得作者写的不错，给个在看关注一波，后续还有更多精彩内容推出。</li>
<li><img src="https://gitee.com/chenjiabing666/Blog-file/raw/master/%E4%B8%83%E7%A7%92%E7%BC%96%E7%A8%8B.jpg" alt=""></li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>写的可还行？</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.jpg" alt="不才陈某 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    
	<div>
	
<div>
      
        
      
</div>

  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
</div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Mybatis/" rel="tag"><i class="fa fa-tag"></i> Mybatis</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/04/20/Mybatis入门之基本操作！！！/" rel="next" title="Mybatis入门之基本操作！！！">
                <i class="fa fa-chevron-left"></i> Mybatis入门之基本操作！！！
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/04/20/Mybatis.动态SQL，你真的会了吗？/" rel="prev" title="Mybatis.动态SQL，你真的会了吗？">
                Mybatis.动态SQL，你真的会了吗？ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/header.jpg"
                alt="不才陈某" />
            
              <p class="site-author-name" itemprop="name">不才陈某</p>
              <p class="site-description motion-element" itemprop="description">本站是不才陈某的技术分享博客。内容涵盖Java后端技术、Spring Boot、微服务架构、系统安全、前端、系统监控等相关的研究与知识分享。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">63</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://juejin.im/user/1556564194374926" target="_blank" title="掘金">
                      
                        <i class="fa fa-fw fa-globe"></i>掘金</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/xiao-ming-64-34-45" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://blog.csdn.net/qq_34162294" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-globe"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/chenjiabing666/BlogImage/raw/master/myjszl_log.png" target="_blank" title="微信公众号">
                      
                        <i class="fa fa-fw fa-globe"></i>微信公众号</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                推荐阅读
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.pexels.com/zh-cn/" title="Pexels" target="_blank">Pexels</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ityouknow.com/" title="纯洁的微笑" target="_blank">纯洁的微笑</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是结果映射？"><span class="nav-text">什么是结果映射？</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何映射？"><span class="nav-text">如何映射？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#别名映射"><span class="nav-text">别名映射</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#驼峰映射"><span class="nav-text">驼峰映射</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#配置文件开启驼峰映射"><span class="nav-text">配置文件开启驼峰映射</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#配置类中开启驼峰映射【简单了解，后续源码章节着重介绍】"><span class="nav-text">配置类中开启驼峰映射【简单了解，后续源码章节着重介绍】</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#resultMap映射"><span class="nav-text">resultMap映射</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#高级结果映射"><span class="nav-text">高级结果映射</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#关联-association"><span class="nav-text">关联(association)</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#例子"><span class="nav-text">例子</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#关联的嵌套-Select-查询【可以忽略】"><span class="nav-text">关联的嵌套 Select 查询【可以忽略】</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#关联的嵌套结果映射【重点】"><span class="nav-text">关联的嵌套结果映射【重点】</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#总结-1"><span class="nav-text">总结</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#集合collection"><span class="nav-text">集合collection</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#集合的嵌套-Select-查询【可以忽略】"><span class="nav-text">集合的嵌套 Select 查询【可以忽略】</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#集合的嵌套结果映射【重点】"><span class="nav-text">集合的嵌套结果映射【重点】</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结-2"><span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">不才陈某</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">143.1k</span>
  
</div>

<!--





  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>

-->

<div>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>




<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共143.1k字</span>
</div>

        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'RtlQOgOT3M0hgyMeogykSQjT-gzGzoHsz',
        appKey: 'vSCxLU88wnXVf0Pa8mwJrCPm',
        placeholder: '原创不易，欢迎各位指正',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
